<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Model\User;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Utils\Context;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class AuthMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @Inject
     * @var RequestInterface
     */
    protected $request;


    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $identity = $this->request->input('identity');
        $user = User::query()->where('identity', $identity)->first();
        if (!$user) {
            $response = Context::get(ResponseInterface::class);
            $data = json_encode([
                'code' => -1,
                'message' => '请先登录',
                'data' => null
            ]);
            return $response->withBody(new SwooleStream($data));
        }
        Context::set('user', $user);
        return $handler->handle($request);
    }
}